﻿using Microsoft.AspNetCore.Http;

namespace Easy.Common.Extension
{
    /// <summary>
    /// HttpContextExtensions
    /// </summary>
    public static class HttpContextExtensions
    {
        /// <summary>
        /// 获取客户IP
        /// </summary>
        /// <param name="context">请求</param>
        /// <returns>返回结果</returns>
        public static string GetClientIP(this HttpContext context)
        {
            string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "";
            if (ip.IsNullOrWhiteSpace())
            {
                ip = context.Connection.RemoteIpAddress.ToString();
                return ip;
            }

            string[] temp;
            bool isErr = false;
            if (ip.Length > 15)
            {
                isErr = true;
            }
            else
            {
                temp = ip.Split('.');
                if (temp.Length == 4)
                {
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (temp[i].Length > 3)
                        {
                            isErr = true;
                        }
                    }
                }
                else
                {
                    isErr = true;
                }
            }
            if (isErr)
            {
                return "1.1.1.1";
            }
            else
            {
                return ip;
            }

        }
        /// <summary>
        /// 判断是否ajax
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回结果</returns>
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            ArgumentNullException.ThrowIfNull(request);
            return request.Headers.ContainsKey("X-Requested-With") &&
                 request.Headers["X-Requested-With"].Equals("XMLHttpRequest");
        }
    }
}